package flexo.input.entity;

import flexo.input.Event;
import flexo.math.Coords;
import flexo.math.Vector;
import flexo.scene.Node;

public class Cursor extends Entity
{
	protected Vector position;
	protected Coords screenSize;
		
	public static final String CURSOR_UP = "CURSOR_UP";
	public static final String CURSOR_DOWN = "CURSOR_DOWN";
	public static final String CURSOR_LEFT = "CURSOR_LEFT";
	public static final String CURSOR_RIGHT = "CURSOR_RIGHT";
	
	public Cursor()
	{
		flexo.graphic.GraphicSystem gs = (flexo.graphic.GraphicSystem)flexo.Kernel.getSystem(flexo.graphic.GraphicSystem.ID);
		screenSize = new Coords(gs.getDisplayMode().x,gs.getDisplayMode().y);
		position = new Vector(screenSize.x/2, screenSize.y/2, 1);
	}
	
	@Override
	public boolean attachTo(Node n)
	{
		boolean result = super.attachTo(n);
		if (result)
		{
			updatePosition();
		}
		return result;
	}
	
	protected void updatePosition()
	{
		// Clamp the mouse position to the screen resolution
		if (position.x < 0)
		{
			position.x = 0;
		}
		else
		{
			float width = screenSize.x;
			if (position.x > width)
			{
				position.x = width;
			}
		}
		
		if (position.y < 0)
		{
			position.y = 0;
		}	
		else
		{
			float height = screenSize.y;
			if (position.y > height)
			{
				position.y = height;
			}
		}
		
		if (exclusiveNode != null)
		{
			exclusiveNode.setPosition(position);
		}
	}

	@Override
	protected void update(Event e, float step)
	{
		if (e.check(CURSOR_UP))
		{
			position.y += step;
		}
		else if (e.check(CURSOR_DOWN))
		{	
			position.y -= step;
		}
		else if (e.check(CURSOR_LEFT))
		{			
			position.x -= step;
		}
		else if (e.check(CURSOR_RIGHT))
		{			
			position.x += step;
		}
		updatePosition();
	}
}
